package com.hnqcgczy.controller;

import com.hnqcgczy.utils.MathCaptchaGenerator;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet("/CaptchaServlet")
public class CaptchaServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 生成验证码
        MathCaptchaGenerator.MathCaptcha captcha = MathCaptchaGenerator.generateCaptcha(); // 生成随机加减法表达式
        BufferedImage image = MathCaptchaGenerator.createCaptchaImage(captcha.getExpression()); // 创建验证码图片
        // 将验证码文本保存到Session中，以便后续验证
        request.getSession().setAttribute("captcha", captcha.getResult());
        // 将图片输出到HTTP响应流中
        response.setContentType("image/png");
        ImageIO.write(image, "png", response.getOutputStream());
    }
}
